package com.rtsapp.server.network.protocol.command.crypto;

import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.network.protocol.command.CommandChannelInitializer;
import com.rtsapp.server.network.protocol.crypto.IAppChannelInitializer;
import com.rtsapp.server.network.protocol.crypto.server.ServerRSAHandshake;
import com.rtsapp.server.network.protocol.crypto.server.ServerRSAHandshakeKey;
import io.netty.channel.socket.SocketChannel;


/**
 * 连接加密的Crypto
 */
public class CryptoCommandChannelInitializer extends CommandChannelInitializer {

	private static Logger LOGGER = LoggerFactory.getLogger(CryptoCommandChannelInitializer.class);

	//RSA连接握手的Key
	private final ServerRSAHandshakeKey handshakeKey;

	public CryptoCommandChannelInitializer(ServerRSAHandshakeKey handshakeKey) {
		this.handshakeKey = handshakeKey;
	}


	@Override
	protected void initChannel(SocketChannel ch) throws Exception {

		try {
			ServerRSAHandshake handshake = new ServerRSAHandshake(ch, new OriginChannelInitializer(), handshakeKey);
			handshake.start();
		}catch ( Throwable ex ){
			LOGGER.error( ex, "CryptoCommandChannelInitializer int error" );
			ch.close();
		}
	}

	private void originInitChannel( SocketChannel ch ) throws Exception{
		super.initChannel( ch );
	}

	public class OriginChannelInitializer implements IAppChannelInitializer {

		@Override
		public void initChannel(SocketChannel ch)  throws Exception {
			CryptoCommandChannelInitializer.this.originInitChannel( ch );
		}

	}
}
